import React, { FC, useEffect } from 'react';
import { FormInstance } from 'antd/lib/form';
import { Spin } from 'antd';
import ProTable, { ProColumns } from '@/components/ProTable';
import useCardModel from '@/pages/Card/useCardModel';
import { CardTypeReturnType } from '@/pages/Card/API';
import { useUnmount } from 'ahooks';
import moment, { Moment } from 'moment';

const OpenCardForm: FC<{ formRef: React.MutableRefObject<FormInstance | undefined> }> = ({
  formRef,
}) => {
  const { cardTypeList = [], cardInfo, getCardInfoLoading, userList } = useCardModel((model) => [
    model.cardTypeList,
    model.cardInfo,
    model.userList,
    model.getCardInfoLoading,
  ]);
  useUnmount(() => {
    formRef.current?.resetFields();
  });

  //List转换枚举
  const cardTypeListEnum = cardTypeList.reduce(
    (pre: { [key: number]: { text: string } }, item: { name: string; typeId: number }) => {
      pre[item.typeId] = { text: item.name };
      return pre;
    },
    {},
  );
  //List转换枚举
  const userTypeListEnum = (userList || []).reduce(
    (pre: { [key: number]: { text: string } }, item: { name: string; id: number }) => {
      pre[item.id] = { text: item.name };
      return pre;
    },
    {},
  );

  const columns: ProColumns<CardTypeReturnType>[] = [
    {
      title: '卡号:',
      rules: [
        {
          required: true,
        },
      ],
      formItemProps: {
        disabled: true,
      },
      dataIndex: 'cardNo',
    },
    {
      title: '卡片类型:',
      rules: [
        {
          required: true,
        },
      ],
      formItemProps: {
        disabled: true,
      },
      dataIndex: 'cardType',
      valueEnum: cardTypeListEnum,
    },
    {
      title: '截止时间:',
      rules: [
        {
          required: true,
        },
      ],
      formItemProps: {
        disabledDate: (current: any) => {
          return current && current < moment().startOf('day');
        },
        format: 'YYYY-MM-DD HH:mm:ss',
        showTime: false,
        onChange: (dates: Moment) => {
          formRef.current?.setFieldsValue({
            validPeriod: moment(dates).startOf('day'),
          });
        },
      },
      dataIndex: 'validPeriod',
      valueType: 'dateTime',
    },
    {
      title: '使用者:',
      rules: [
        {
          required: true,
        },
      ],
      dataIndex: 'userId',
      valueEnum: userTypeListEnum,
    },
    {
      title: '备注:',
      dataIndex: 'rec',
      valueType: 'textarea',
    },
  ];
  useEffect(() => {
    cardInfo &&
      formRef.current?.setFieldsValue({
        cardNo: cardInfo.cardNo,
        cardType: cardInfo.cardType.toString(),
      });
  }, [cardInfo]);

  return (
    <Spin spinning={getCardInfoLoading}>
      <ProTable<CardTypeReturnType>
        form={{ layout: 'vertical', autoComplete: 'off' }}
        columns={columns}
        type={'form'}
        formRef={formRef}
      />
    </Spin>
  );
};
export default OpenCardForm;
